package edu.aynu.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 用户的信息
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable, UserDetails {
    private Integer id;
    private String username;    //账号
    private String password;    //密码
    private String email;       //邮箱
    private String phone;      //手机号（账号）
    private Integer gen;      //年龄，0代表男，1代表女
    private String name;     //真实姓名
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date registerTime;  //注册时间
    private Integer activation; //用户是否激活，1代表激活
    private List<edu.aynu.entity.Role> roles;  //权限表

    /**
     * 邮箱注册
     * 用户注册成功之后，把账号密码写入数据库
     * 密码初始化默认都是  123
     * 注册时间    为当前时间
     * 默认账户以及激活
     * @param email
     */
    public User(String email,String username,String password){
        this.username = username;
        this.password = "123";
        this.email = email;
        this.registerTime =new Date();
        this.activation = 1;
    }

    /**
     * 账号密码注册
     * @param username
     * @param password
     */
    public User(String username,String password){
        this.username = username;
        this.password = password;
        this.email = "111111111@qq.com";
        this.registerTime =new Date();
        this.activation = 1;
    }

    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (edu.aynu.entity.Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return authorities;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
